package pers.w.chaptertalk.reader;

import android.annotation.SuppressLint;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Switch;
import android.widget.TableLayout;

import androidx.constraintlayout.widget.ConstraintLayout;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import pers.w.chaptertalk.R;

class SettingWindow {
    private TableLayout layout;
    private Spinner spinner_fonts,
            spinner_text_color_list,
            spinner_background_color_list;
    private SeekBar sb_text_color, sb_background_color, sb_text_size,
            sb_row_spacing, sb_paragraph_spacing;
    private ReaderActivity reader;
    private RadioButton rb_l_r, rb_t_b;
    private RadioGroup rg_screenOn;
    private static final File fonts_dir = new File("/storage/emulated/0/Android/data/fonts");

    @SuppressLint("InflateParams")
    SettingWindow(final ReaderActivity reader) {
        this.reader = reader;
        LayoutInflater inflater = LayoutInflater.from(reader);
        layout = inflater.inflate(R.layout.reader_setting, null).findViewById(R.id.tl_setting);
        layout.setFocusable(true);
        layout.setClickable(true);//获得焦点，才不会让后面的控件响应

        ConstraintLayout cl = reader.findViewById(R.id.cl_reader);//获得根容器，父窗口
        ConstraintLayout.LayoutParams lp = new ConstraintLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setMargins(1, 0, 1, 0);
        lp.bottomToBottom = R.id.cl_reader;
        layout.setVisibility(View.GONE);//开局隐藏
        cl.addView(layout, lp);

        spinner_fonts = layout.findViewById(R.id.spinner_fonts);
        spinner_background_color_list = layout.findViewById(R.id.spinner_background_color_list);
        spinner_text_color_list = layout.findViewById(R.id.spinner_text_color_list);

        setSpinner_Listen();
        sb_text_color = layout.findViewById(R.id.sb_text_color);
        sb_background_color = layout.findViewById(R.id.sb_background_color);
        sb_text_size = layout.findViewById(R.id.sb_text_size);
        sb_row_spacing = layout.findViewById(R.id.sb_row_spacing);
        sb_paragraph_spacing = layout.findViewById(R.id.sb_paragraph_spacing);

        setSeekBarListen();

        Button btn_default = layout.findViewById(R.id.btn_default);
        btn_default.setOnClickListener(v -> {
            reader.control.defaultSetting();
            reader.postReFill();
        });
        if (!fonts_dir.exists()) fonts_dir.mkdir();
        getColors();

        rb_l_r = layout.findViewById(R.id.rb_l_r);
        rb_t_b = layout.findViewById(R.id.rb_t_b);
        rb_l_r.setOnClickListener(v -> {
            rb_t_b.setChecked(false);
            reader.control.setOrientation(LinearLayout.HORIZONTAL);
        });
        rb_t_b.setOnClickListener(v -> {
            rb_l_r.setChecked(false);
            reader.control.setOrientation(LinearLayout.VERTICAL);
        });
        rg_screenOn = reader.findViewById(R.id.rg_screen_on);
        rg_screenOn.setOnCheckedChangeListener((group, checkedId) -> {
            switch(checkedId){
                case R.id.rb_by_system:
                    reader.setScreenOn(-1);
                    reader.control.setScreenOnTime("0");
                    break;
                case R.id.rb_5m:
                    reader.setScreenOn(300);//second
                    reader.control.setScreenOnTime("1");
                    break;
                case R.id.rb_10m:
                    reader.control.setScreenOnTime("2");
                    reader.setScreenOn(600);
                    break;
            }
        });
    }
private int[] radioButtons= new int[]{R.id.rb_by_system,R.id.rb_5m,R.id.rb_10m};
    private void setSeekBarListen() {
        SeekBar.OnSeekBarChangeListener seeker_listener = new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

                switch (seekBar.getId()) {
                    case R.id.sb_text_color:
                        reader.control.setTextColor(sb_text_color.getProgress() | 0xA0000000);//全不透明太刺眼
                        break;
                    case R.id.sb_background_color:
                        reader.control.setBackgroundColor(sb_background_color.getProgress() | 0xF0000000);
                        break;
                    case R.id.sb_text_size:
                        reader.control.setTextSize(seekBar.getProgress());
                        reader.postReFill();//这里必须要用post方法传递一个消息回去，不然没有重绘完成等不到行数
                        break;
                    case R.id.sb_row_spacing:
                        reader.control.setRowSpacing(seekBar.getProgress());
                        reader.postReFill();
                        break;
                    case R.id.sb_paragraph_spacing:
                        reader.control.setParagraph_spacing(seekBar.getProgress());
                        reader.postReFill();
                        break;
                }
            }
        };
        sb_text_color.setOnSeekBarChangeListener(seeker_listener);
        sb_background_color.setOnSeekBarChangeListener(seeker_listener);
        sb_text_size.setOnSeekBarChangeListener(seeker_listener);
        sb_row_spacing.setOnSeekBarChangeListener(seeker_listener);
        sb_paragraph_spacing.setOnSeekBarChangeListener(seeker_listener);
    }

    private void setSpinner_Listen() {
        AdapterView.OnItemSelectedListener spinner_listener = new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                switch (parent.getId()) {
                    case R.id.spinner_text_color_list:
                        if (position > 0 && colors[position] != reader.control.getTextColor()) {
                            reader.control.setTextColor(colors[position]);
                            sb_text_color.setProgress(colors[position] & 0x00FFFFFF);
                        }

                        break;
                    case R.id.spinner_background_color_list:
                        if (position > 0 && colors[position] != reader.control.getBackgroundColor()) {
                            reader.control.setBackgroundColor(colors[position]);
                            sb_background_color.setProgress(colors[position] & 0x00FFFFFF);
                        }

                        break;
                    case R.id.spinner_fonts:
                        if (position > 0) {
                            reader.control.setFont(fonts_dir.getAbsolutePath() + "/" + spinner_fonts.getSelectedItem().toString());
                            reader.postReFill();
                        }
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        };
        spinner_fonts.setOnItemSelectedListener(spinner_listener);
        spinner_background_color_list.setOnItemSelectedListener(spinner_listener);
        spinner_text_color_list.setOnItemSelectedListener(spinner_listener);

    }

    private SpinnerAdapter adapter = null;
    // private String[] colorNames;
    private int[] colors;

    private void getColors() {
        Resources res = reader.getResources();
        //  colorNames = res.getStringArray(R.array.color_names);
        colors = res.getIntArray(R.array.color_values);
    }

    void setVisibility(boolean visibility) {
        layout.setVisibility(visibility ? View.VISIBLE : View.GONE);

        if (visibility) {
            layout.startAnimation(reader.ltoC);

            if (null == adapter) {
                String[] files = fonts_dir.list();
                List<String> list = new ArrayList<>();
                list.add("选 择");

                if (null != files) {
                    for (String file : files) {
                        if (file.toUpperCase().endsWith(".TTF"))
                            list.add(file);
                    }
                }
                adapter = new ArrayAdapter<>(reader, android.R.layout.simple_spinner_item, list);
                spinner_fonts.setAdapter(adapter);

            }

            boolean check= reader.control.getOrientation() == LinearLayout.HORIZONTAL;
            rb_l_r.setChecked(check);
            rb_t_b.setChecked(!check);

            sb_text_size.setProgress(reader.control.getTextSize());
            sb_row_spacing.setProgress(reader.control.getRowSpacing());
            sb_paragraph_spacing.setProgress(reader.control.getParagraph_spacing());

            int color = reader.control.getTextColor();
            sb_text_color.setProgress(color & 0x00FFFFFF);
            int index = indexOfColors(color);
            if (index != -1) spinner_text_color_list.setSelection(index);

            color = reader.control.getBackgroundColor();
            sb_background_color.setProgress(color & 0x00FFFFFF);
            index = indexOfColors(color);
            if (index != -1) spinner_background_color_list.setSelection(index);

            rg_screenOn.check(radioButtons[Integer.parseInt (reader.control.getScreenOnTime())]);
        } else {
            reader.control.save_setting();
            layout.startAnimation(reader.ctoL);
        }
    }

    private int indexOfColors(int color) {
        for (int i = 1; i < colors.length; i++) {//从1 开始，0是选择
            if (colors[i] == color) {
                return i;
            }
        }
        return -1;
    }

    boolean isVisibility() {
        return layout.getVisibility() == View.VISIBLE;
    }
}
